<template>
  <view class="container">
    <!-- 标题区域 -->
    <view class="title-section">
      <input placeholder="标题" class="title-input" placeholder-class="placeholder" v-model="formData.title"
        maxlength="30" @input="checkTitleLength" />
      <view class="title-meta">
        <text class="time">{{currentTime}}</text>
        <text class="title-count">{{titleCount}}/30</text>
      </view>
    </view>

    <!-- 内容区 -->
    <view class="content-section">
      <textarea placeholder="这一刻的想法……" class="content-input" placeholder-class="placeholder" maxlength="300"
        v-model="formData.content" @input="updateWordCount"></textarea>
      <text class="word-count">{{wordCount}}/300</text>
    </view>

    <!-- 关联书籍 -->
    <view class="book-section">
      <text class="section-title">书籍</text>
      <picker mode="selector" :range="bookList" range-key="title" @change="onBookChange" :value="selectedBookIndex">
        <view class="picker">
          <text class="picker-text">{{selectedBook.title || '请选择书籍'}}</text>
          <uni-icons type="arrowright" size="16" color="#999"></uni-icons>
        </view>
      </picker>
    </view>

    <!-- 图片上传 -->
    <view class="image-section">
      <text class="section-title">图片</text>
      <uni-file-picker v-model="formData.images" file-mediatype="image" mode="grid" :image-styles="imageStyles"
        :limit="4" @select="onSelect" @delete="onDelete"></uni-file-picker>
      <text class="upload-tip">最多可上传4张图片</text>
    </view>

    <!-- 标签 -->
    <view class="tag-section">
      <text class="section-title">标签</text>
      <view class="tags-container">
        <view v-for="(tag, index) in formData.tags" :key="index" class="tag-item">
          <text>#{{tag}}</text>
          <uni-icons type="close" size="14" color="#999" @click="removeTag(index)"></uni-icons>
        </view>
        <input v-model="newTag" placeholder="输入标签" class="tag-input" placeholder-class="placeholder" maxlength="10"
          @confirm="addTag" />
      </view>
    </view>

    <!-- 确认按钮 -->
    <view class="action-bar">
      <button class="confirm-btn" @click="submitNote">{{isEditMode ? '更新' : '完成'}}</button>
    </view>
  </view>
</template>

<script>
  import {
    mapState,
  } from 'vuex'
  export default {
    props: {
      // 是否编辑模式
      isEditMode: {
        type: Boolean,
        default: false
      },
      // 编辑时的初始数据
      initialData: {
        type: Object,
        default: () => ({})
      }
    },
    data() {
      return {
        formData: {
          title: '',
          content: '',
          images: [],
          tags: [],
          bId: null
        },
        newTag: '',
        wordCount: 0,
        titleCount: 0,
        selectedBook: {},
        selectedBookIndex: -1,
        imageStyles: {
          width: 120,
          height: 120,
          border: {
            color: "#eee",
            width: 1,
            style: "solid",
            radius: "4px"
          }
        }
      }
    },
    computed: {
      ...mapState('m_book', ['bookList']),
      currentTime() {
        const now = new Date()
        const month = now.getMonth() + 1
        const day = now.getDate()
        const hours = now.getHours()
        const minutes = now.getMinutes()
        return `${month}月${day}日 ${hours}:${minutes < 10 ? '0' + minutes : minutes}`
      }
    },
    watch: {
      // 监听初始数据变化，用于编辑模式
      initialData: {
        handler(newVal) {
          if (newVal && this.isEditMode) {
            this.initFormData(newVal)
          }
        },
        immediate: true,
        deep: true
      }
    },
    methods: {
      initFormData(data) {
        // 初始化表单数据
        this.formData = {
          title: data.title || '',
          content: data.content || '',
          images: data.images || [],
          tags: data.tags || [],
          bId: data.bId || null
        }

        // 更新字数统计
        this.titleCount = this.formData.title.length
        this.wordCount = this.formData.content.length

        // 设置选中的书籍
        if (data.bId) {
          const index = this.bookList.findIndex(book => book.id === data.bId)
          if (index !== -1) {
            this.selectedBook = this.bookList[index]
            this.selectedBookIndex = index
          }
        }
      },

      checkTitleLength(e) {
        this.titleCount = e.detail.value.length
      },

      updateWordCount(e) {
        this.wordCount = e.detail.value.length
      },

      onBookChange(e) {
        const index = e.detail.value
        this.selectedBook = this.bookList[index]
        this.selectedBookIndex = index
        this.formData.bId = this.selectedBook.id
      },

      onSelect(e) {
        console.log('选择图片:', e)
        uni.showLoading({
          title: '上传中...'
        })
        setTimeout(() => {
          uni.hideLoading()
        }, 1500)
      },

      onDelete(e) {
        console.log('删除图片:', e)
      },

      addTag() {
        const tag = this.newTag.trim()
        if (tag && !this.formData.tags.includes(tag)) {
          this.formData.tags.push(tag)
          this.newTag = ''
        }
      },

      removeTag(index) {
        this.formData.tags.splice(index, 1)
      },

      submitNote() {
        if (!this.validateForm()) return

        const noteData = {
          ...this.formData,
        }
        if(!this.isEditMode)noteData.createTime=new Date().toISOString()
        else noteData.updateTime=new Date().toISOString()

        console.log('提交的笔记数据:', noteData)

        uni.showLoading({
          title: this.isEditMode ? '更新中...' : '提交中...'
        })

        // 这里应该是调用API接口
        setTimeout(() => {
          uni.hideLoading()
          uni.showToast({
            title: this.isEditMode ? '更新成功' : '添加成功',
            icon: 'success'
          })

          // 通知父组件操作完成
          this.$emit('submit', noteData)

          // 如果是添加模式，返回上一页
          if (!this.isEditMode) {
            setTimeout(() => {
              uni.navigateBack()
            }, 1500)
          }
        }, 2000)
      },

      validateForm() {
        if (!this.formData.title.trim()) {
          uni.showToast({
            title: '请输入标题',
            icon: 'none'
          })
          return false
        }

        if (this.formData.title.length > 30) {
          uni.showToast({
            title: '标题不能超过30个字',
            icon: 'none'
          })
          return false
        }

        if (!this.formData.content.trim()) {
          uni.showToast({
            title: '请输入内容',
            icon: 'none'
          })
          return false
        }

        if (this.formData.bId == null) {
          uni.showToast({
            title: '请选择书籍',
            icon: 'none'
          })
          return false
        }

        return true
      }
    }
  }
</script>

<style lang="scss">
  /* 保持原有的样式不变 */
  .container {
    padding: 20rpx;
    background-color: #f8f8f8;
    min-height: 100vh;
    padding-bottom: 120rpx;
  }

  .placeholder {
    color: #999999;
  }

  .title-section {
    margin-bottom: 30rpx;
    padding: 20rpx;
    background-color: #fff;
    border-radius: 12rpx;

    .title-input {
      font-size: 36rpx;
      font-weight: bold;
      height: 50rpx;
      color: #333;
      width: 100%;
    }

    .title-meta {
      display: flex;
      justify-content: space-between;
      margin-top: 10rpx;

      .time {
        font-size: 24rpx;
        color: #999;
      }

      .title-count {
        font-size: 24rpx;
        color: #999;
      }
    }
  }

  .content-section {
    margin-bottom: 30rpx;
    padding: 20rpx;
    background-color: #fff;
    border-radius: 12rpx;

    .content-input {
      width: 100%;
      min-height: 300rpx;
      font-size: 28rpx;
      line-height: 1.6;
    }

    .word-count {
      font-size: 24rpx;
      color: #999;
      text-align: right;
      display: block;
      margin-top: 10rpx;
    }
  }

  .book-section {
    margin-bottom: 30rpx;
    padding: 20rpx;
    background-color: #fff;
    border-radius: 12rpx;

    .picker {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx 0;

      .picker-text {
        font-size: 28rpx;
        color: #333;
      }
    }
  }

  .image-section {
    margin-bottom: 30rpx;
    padding: 20rpx;
    background-color: #fff;
    border-radius: 12rpx;

    .upload-tip {
      font-size: 24rpx;
      color: #999;
      margin-top: 10rpx;
      display: block;
    }
  }

  .tag-section {
    margin-bottom: 30rpx;
    padding: 20rpx;
    background-color: #fff;
    border-radius: 12rpx;

    .tags-container {
      display: flex;
      flex-wrap: wrap;
      margin-top: 20rpx;

      .tag-item {
        display: flex;
        align-items: center;
        background-color: #f0f0f0;
        border-radius: 40rpx;
        padding: 8rpx 20rpx;
        margin-right: 15rpx;
        margin-bottom: 15rpx;
        font-size: 26rpx;
      }

      .tag-input {
        height: 60rpx;
        min-width: 150rpx;
        font-size: 26rpx;
        margin-bottom: 15rpx;
      }
    }
  }

  .action-bar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 20rpx;
    background-color: #fff;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

    .confirm-btn {
      background-color: #007AFF;
      color: #fff;
      border-radius: 50rpx;
      height: 80rpx;
      line-height: 80rpx;
      font-size: 32rpx;
    }
  }

  .section-title {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
    display: block;
  }
</style>
